<template>
  <div class="publish">
    <!--1. 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章发布</el-breadcrumb-item>
    </el-breadcrumb>
    <!--2. 卡片组件 -->
    <el-card class="box-card">
      <!--3. 表单结构 -->
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>

        <el-form-item label="栏目" prop="categories">
          <!-- 全选按钮 -->
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <!-- 小选编组  @change="handleCheckedCitiesChange"-->
          <el-checkbox-group
            v-model="form.categories"
            @change="handleCheckedCitiesChange"
          >
            <!-- 小选列表 -->
            <el-checkbox
              v-for="item in cateList"
              :key="item.id"
              :label="item.id"
              name="categories"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--4. 富文本框 -->
        <el-form-item label="内容">
          <VueEditor :config="config" ref="vueEditor" />
        </el-form-item>
        <!--5. 封面 cover-->
        <el-form-item label="封面">
          <el-upload
            :action="$baseURL + '/upload'"
            list-type="picture-card"
            :headers="headers"
            :on-success="onSuccess"
            :on-remove="onRemove"
            :limit="3"
            :on-exceed="onExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getCategoryAPI } from "@/apis/category";
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import { getToken } from "../../utils/locaData";
import { PostPubLishAPI } from "@/apis/news";
export default {
  components: {
    VueEditor,
  },
  data() {
    return {
      //用来提交表单数据
      form: {
        title: "", //标题
        categories: [], //栏目id
        type: 1, //类型
        content: "", //文章内容
        cover: [], //封面图片ID集合
      },
      rules: {
        //标题
        title: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        //栏目
        categories: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个栏目",
            trigger: "change",
          },
        ],
      },
      headers: { Authorization: getToken() },
      cateList: [],
      checkAll: false,
      isIndeterminate: true,
      //url name headers按接口文档的参数
      config: {
        // 上传图片的配置
        uploadImage: {
          url: this.$baseURL + "/upload",
          name: "file",
          //这里不是axios发送请求,所以需要独立配置请求头
          headers: { Authorization: getToken() },
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          //内部要调用this,所以要改成箭头函数写法
          uploadSuccess: (res, insert) => {
            // console.log(res);
            if (res.data.message === "文件上传成功") {
              //用于插入富文本编辑器(图片完整路径)
              insert(this.$baseURL + res.data.data.url);
            } else {
              this.$message.warning("文件上传有误");
            }
          },
        },
      },
    };
  },
  async created() {
    // console.log(this.$baseURL);
    //获取栏目数据
    const res = await getCategoryAPI();
    // console.log(res);
    this.cateList = res.data.data.slice(2);
  },
  methods: {
    onExceed() {
      this.$message.warning("不能超过三张");
    },
    onSuccess(res) {
      //封面数组也要按接口文档要求来收集
      this.form.cover.push({ id: res.data.id });
    },
    //封面移除
    onRemove(file) {
      const id = file.response.data.id;
      this.form.cover = this.form.cover.filter((item) => item.id !== id);
    },
    //发布文章按钮 -发布前一定要检查数据 是否为空,字段是否和后端一致
    async onSubmit() {
      //数据检查1-标题不能为空
      if (/^.{3,20}$/.test(this.form.title.trim()) === false) {
        return this.$message.warning("标题不符合规则");
      }
      //数据检查2-栏目不能为空
      if (this.form.categories.length === 0) {
        return this.$message.warning("至少选择一个栏目");
      }
      //数据检查3-封面不能为空
      if (this.form.cover.length === 0) {
        return this.$message.warning("至少添加一个封面");
      }
      //如果文章类型,type为1
      if (this.form.type === 1) {
        //按照后端字段要求,保存到content字段中,为发布文章做准备
        this.form.content = this.$refs.vueEditor.editor.root.innerHTML;
        //数据检查4-文章内容不能为空
        if (this.form.content === "<p><br></p>") {
          return this.$message.warning("新闻内容不能为空");
        }
      }
      console.log("222", this.form);
      //转换后端所需的格式-栏目数据需要调整
      const data = {
        //展开原本的用于双向绑定form表单数据
        ...this.form,
        //后端要求
        categories: this.form.categories.map((item) => {
          return { id: item };
        }),
      };
      console.log(data);
      //调用发布文章API
      let res = await PostPubLishAPI(data);
      if (res.data.message === "文章发布成功") {
        this.$message.success("恭喜!文章发布成功");
        this.$router.push("/home/post_list");
      }
      console.log(res);
    },
    //全选按钮
    handleCheckAllChange(val) {
      // console.log(val);
      this.form.categories =
        val === true ? this.cateList.map((item) => item.id) : [];
      //取消不确定状态
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      console.log(value);
      let checkedCount = value.length;
      // 全选状态:选中栏目长度:选中状态的长度和原数组长度是否一致
      this.checkAll = checkedCount === this.cateList.length;

      // //添加不确定状态
      //不全选中状态
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },
  },
};
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 20px;
}
</style>